<?php
/**
 * Created by PhpStorm.
 * User: tony
 * Date: 2018/6/4
 * Time: 11:20
 */

namespace app\modules\v1\controllers;

use app\config\Status;
use app\models\interfaces;
use app\modules\v1\controllers\parent\ParentController;
use Yii;
use yii\data\ActiveDataProvider;
use yii\helpers\Inflector;

class InterfacesController extends ParentController
{
    private function getAllApiFromDir(){
        $baseDir = Yii::$app->basePath;

        // 此次目录如果为模块，增加模块目录
        $controllerDir = $baseDir.'/modules/v1/controllers/';
        $dirHandle = opendir($controllerDir);
        $apiArr = [];
        if($dirHandle){
            // 遍历控制器目录下的所有控制器类文件
            while(($file=readdir($dirHandle))!==false) {
                $fileRealPath = realpath($controllerDir.$file);
                if($file==='.' || $file==='..' || is_dir($fileRealPath)){
                    continue;
                }
                $controllerIDStr = (substr($file, 0 , -14));
                $controllerIDStr = Inflector::camel2id($controllerIDStr);

                // 读取单个控制器文件
                $fileHandle = fopen($controllerDir. $file, "r");
                if ($fileHandle) {
                    // 遍历每一行
                    while (($line = fgets($fileHandle)) !== false) {
                        // 正则匹配每一行内容，符合规则/public function action(.*?)\(/，并抓取匹配到的内容
                        if (preg_match('/public function action(.*?)\(/', $line, $display)):
                            // 获取内容必须大于2，防止actions方法被抓取
                            if (strlen($display[1]) > 2):
                                $actionIdStr = Inflector::camel2id($display[1]);
                                array_push($apiArr, $controllerIDStr.'/'.$actionIdStr);
                            endif;
                        endif;
                    }
                }
            }
        }
        return $apiArr;
    }

   public function actionGain() {
       $apiID = $this->getAllApiFromDir();
       $result = array();
       foreach ($apiID as $k => $v) {
           $result[$k] = explode('/', $v);
       }
       foreach ($result as $k => $v) {
            $res = Interfaces::findOne(['controller_id' => $v[0], 'action_id' => $v[1]]);
            if (!$res) {
                $model = new Interfaces();
                $model->controller_id = $result[$k][0];
                $model->action_id = $result[$k][1];
                $model->save();
            }
        }
   }

   public function actionCreate() {
       $apiID = $this->getAllApiFromDir();
       foreach ($apiID as $k => $v) {
           $model = Interfaces::findOne(['id' => $k+1]);
           if ($model) {
//               $model = new Interfaces();
               $model->auth = $v;
               $model->save();
           }
       }
   }

   public function actionIndex() {
       $params = \Yii::$app->request->getQueryParams();
       $query = Interfaces::find();
       $pageSize = 1000;
       if(isset($params['pageSize'])){
           $pageSize = (int)$params['pageSize'];
       }
       return new ActiveDataProvider([
           // 使用with方法实现贪加载
           'query' => $query,
           // 分页信息
           'pagination' => [
               'pageSize' => $pageSize,
           ],
           // 排序信息
           'sort' => [
               'defaultOrder' => [
                   'id' => SORT_DESC,
               ]
           ],
       ]);
   }

    /**
     * @throws \yii\base\InvalidConfigException
     */
   public function actionUpdate() {
       $data = \Yii::$app->request->getBodyParams();
       if (isset($data['part_ids']) && is_array($data['part_ids'])) {
           $data['part_ids'] = implode(',', $data['part_ids']);
           $data['part_ids'] = trim($data['part_ids'], ',');
       }
       $model = Interfaces::findOne(['id' => $data['id']]);
       $model->load($data, '');

       if ($model->save()) {
           return [
               'bCode' => Status::SUCCESS,
               'bData' => $model,
           ];
       }

       return [
           'bCode' => Status::SUCCESS,
           'bData' => $model->errors,
       ];
   }

   public function actionView() {
       $params = \Yii::$app->request->getQueryParams();
       $result = Interfaces::findOne(['id' => $params['id']]);
       if (isset($result['part_ids'])) {
           $result['part_ids'] = explode(',', $result['part_ids']);
       }
       return $result;
   }
}